#include "mainwindow.h"

#include <QVBoxLayout>

#include "reader.h"
#include "writer.h"

MainWindow::MainWindow(int books, int timeout, int readers, int writers, QWidget *parent)
    : QWidget(parent)
    , m_shell(new Shell(books, this))
    , m_control(new ControlWidget(timeout, timeout))
    , m_progress(new ProgressWidget(books, readers + writers))
{
    QVBoxLayout *main = new QVBoxLayout;
    main->addWidget(m_progress);
    main->addWidget(m_control);
    setLayout(main);

    connect(m_shell, SIGNAL(book_added(int)), m_progress, SLOT(new_book()), Qt::QueuedConnection);

    m_thread_pool.setMaxThreadCount(readers + writers);
    for (int i = 0; i < readers; ++i)
    {
        Reader *reader = new Reader(m_shell, timeout, this);
        connect(m_control, SIGNAL(reader_timeout(int)), reader, SLOT(set_timeout(int)), Qt::QueuedConnection);
        connect(reader, SIGNAL(i_m_reading()), m_progress, SLOT(new_working()), Qt::QueuedConnection);
        connect(reader, SIGNAL(i_m_waiting()), m_progress, SLOT(new_waiting()), Qt::QueuedConnection);
        m_thread_pool.start(reader);
    }

    for (int i = 0; i < writers; ++i)
    {
        Writer *writer = new Writer(m_shell, timeout, this);
        connect(m_control, SIGNAL(writer_timeout(int)), writer, SLOT(set_timeout(int)), Qt::QueuedConnection);
        connect(writer, SIGNAL(i_m_editing()), m_progress, SLOT(new_working()), Qt::QueuedConnection);
        connect(writer, SIGNAL(i_m_waiting()), m_progress, SLOT(new_waiting()), Qt::QueuedConnection);
        m_thread_pool.start(writer);
    }
}
